package com.cheyunkeji.er.fragment.evaluate;

import android.app.Dialog;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.activity.ModuleSelectActivity;
import com.cheyunkeji.er.activity.evaluate.EvaluateHomePageActivity;
import com.cheyunkeji.er.activity.evaluate.UploadedCarActivity;
import com.cheyunkeji.er.activity.evaluate.WaitToEvaluateActivity;
import com.cheyunkeji.er.activity.fast_evaluate.CallCenterActivity;
import com.cheyunkeji.er.activity.fast_evaluate.NoticeActivity;
import com.cheyunkeji.er.app.PushMsgManager;
import com.cheyunkeji.er.app.UserInfoManager;
import com.cheyunkeji.er.base.BaseFragment;
import com.cheyunkeji.er.bean.PushMsgBean;
import com.cheyunkeji.er.bean.UserInfo;
import com.cheyunkeji.er.bean.event.RefreshUIEvent;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.utils.ChannelInfoUtil;
import com.cheyunkeji.er.utils.DensityUtil;
import com.cheyunkeji.er.view.SToast;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by Michael on 2017/3/17 10:49.
 */

public class EvaluateMineFragment extends BaseFragment {


    private static final int EVALUATE_LIST_ITEM_SAVED = 1;
    private static final int EVALUATE_LIST_ITEM_UPLOADED = 2;

//    @BindView(R.id.iv_top_bkg)
//    ImageView ivTopBkg;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_tele_number)
    TextView tvTeleNumber;
    @BindView(R.id.civ_photo)
    ImageView civPhoto;
    @BindView(R.id.tv_evaluated_count)
    TextView tvEvaluatedCount;
    @BindView(R.id.tv_uploaded_count)
    TextView tvUploadedCount;
    @BindView(R.id.tv_unupload_count)
    TextView tvUnuploadCount;
//    @BindView(R.id.iv_icon4)
//    ImageView ivIcon4;
//    @BindView(R.id.iv_arrow)
//    ImageView ivArrow;
    @BindView(R.id.rl_uploaded_car)
    RelativeLayout rlUploadedCar;
//    @BindView(R.id.iv_icon1)
//    ImageView ivIcon1;
//    @BindView(R.id.iv_arrow_2)
//    ImageView ivArrow2;
//    @BindView(R.id.iv_unevaluate_car)
//    ImageView ivUnevaluateCar;
    @BindView(R.id.rl_need_evaluate)
    RelativeLayout rlNeedEvaluate;

    private PushMsgManager pushMsgManager;

    //    当前已保存(未上传)项数量
    private int savedCount;

    //    当前已上传项数量
    private int uploadedCount;

    @Override
    protected void doInflaterView(LayoutInflater inflater, ViewGroup container) {
        contentView = inflater.inflate(R.layout.er_frag_evaluate_mine, container, false);
        ButterKnife.bind(this, contentView);
    }

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initView() {

        UserInfo.ChannelListBean currentChannel = ChannelInfoUtil.getCurrentChannelInfo();
        int moduleCount = currentChannel.getIsarchiver() + currentChannel.getIsauction() + currentChannel.getIsrapid() ;

//        if(moduleCount != 0 && moduleCount != 1){
//            llSwitchModule.setVisibility(View.VISIBLE);
//            rlSwitchModule.setOnClickListener(this);
//        }

//      为CircleImageView加载并显示网络图片，根据CircleImageView的Github readme的说明，
//      使用第三方图片加载库去加载网络图片时要除去动画，glide用dontAnimate()除去，picasso用noFade除去

        tvUserName.setText(UserInfoManager.getInstance(this.getActivity()).getRealName());
        String mobile = UserInfoManager.getInstance(MyApplication.getInstance()).getMobile();
        if(mobile.length()>=11) {
            tvTeleNumber.setText(mobile.replaceFirst(mobile.substring(3, 7), "****"));
        }

        civPhoto.setImageResource(R.drawable.d01_wdym_head);
        rlUploadedCar.setOnClickListener(this);
        rlNeedEvaluate.setOnClickListener(this);

    }

    @Override
    protected void initData() {
        showUnreadMsgState();
        showCurrentItemCounts();
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.rl_uploaded_car:
                startActivity(new Intent(getActivity(), UploadedCarActivity.class));
                break;
            case R.id.rl_need_evaluate:
                startActivity(new Intent(getActivity(), WaitToEvaluateActivity.class));
                if (null == pushMsgManager)
                    pushMsgManager = PushMsgManager.getInstance(MyApplication.getInstance(), ChannelInfoUtil.getCurrentChannelInfo().getChannel() + UserInfoManager.getInstance(this.getActivity()).getAccount());
                pushMsgManager.clearNotifyMsgRecordCount(PushMsgManager.MSG_TYPE_QUANMIAN);
                break;
            default:
                break;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {   // 不在最前端显示 相当于调用了onPause();
            return;
        } else {  // 在最前端显示 相当于调用了onResume();
            //网络数据刷新
            showUnreadMsgState();
            showCurrentItemCounts();
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        tvUserName.setText(UserInfoManager.getInstance(this.getActivity()).getRealName());
        String mobile = UserInfoManager.getInstance(MyApplication.getInstance()).getMobile();
        if(mobile.length()>=11) {
            tvTeleNumber.setText(mobile.replaceFirst(mobile.substring(3, 7), "****"));
        }
    }

    private void showUnreadMsgState() {
        if (null == pushMsgManager)
            pushMsgManager = PushMsgManager.getInstance(MyApplication.getInstance(), ChannelInfoUtil.getCurrentChannelInfo().getChannel() + UserInfoManager.getInstance(this.getActivity()).getAccount());
//        if (pushMsgManager.getMsgCount(PushMsgManager.MSG_TYPE_QUANMIAN) == 0) {
//            ivUnevaluateCar.setVisibility(View.GONE);
//        } else {
//            ivUnevaluateCar.setVisibility(View.VISIBLE);
//        }

//        if (pushMsgManager.getMsgCount(PushMsgManager.MSG_TYPE_ZHANNEIXIN) == 0) {
//            ivNotifyUnreadDot.setVisibility(View.GONE);
//        } else {
//            ivNotifyUnreadDot.setVisibility(View.VISIBLE);
//        }
        ((EvaluateHomePageActivity) getActivity()).refreshBottomUnreadMsgCount();
    }

    /**
     * 统一处理推送消息
     *
     * @param msgBean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPushMsgReceived(PushMsgBean msgBean) {
        if (msgBean.getNotice_type() == PushMsgManager.MSG_TYPE_QUANMIAN || msgBean.getNotice_type() == PushMsgManager.MSG_TYPE_ZHANNEIXIN) {
            dealWithPushMsg(msgBean);
            EventBus.getDefault().removeStickyEvent(msgBean);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPushMsgReceived(RefreshUIEvent event) {
        if (event.getEventType() == RefreshUIEvent.TYPE_REFRESH_EVALUATE_MINE_ITEM_COUNTS) {
//            showCurrentItemCounts();
            EventBus.getDefault().removeStickyEvent(event);
        }
    }


    private void getEvaluateItemCounts(final int itemState) {
        HashMap<String, String> params = new HashMap<>();
        //      params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        params.put("state", String.valueOf(itemState));
        ApiClient.postForm(HttpConstants.EVALUATE_CAR_LIST, params, new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                if (e instanceof UnknownHostException || e instanceof SocketException) {
                    SToast.show(R.string.tip_network_error, Gravity.CENTER);
                    return;
                }
            }

            @Override
            public void onResponse(String response, int id) {

                try {
                    JSONObject obj = new JSONObject(response);
                    if (obj.optInt("code", 0) == 1) {

                        if (itemState == EVALUATE_LIST_ITEM_SAVED) {
                            savedCount = obj.optInt("rows");
                            Log.e(TAG, "onResponse: savedCount :  "  +  savedCount  );
                        } else if (itemState == EVALUATE_LIST_ITEM_UPLOADED) {
                            uploadedCount = obj.optInt("rows");
                            Log.e(TAG, "onResponse: uploadedCount : " + uploadedCount );
                        }
                        displayCounts();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        });
    }


    private void displayCounts() {
        tvUnuploadCount.setText(String.valueOf(savedCount));
        tvUploadedCount.setText(String.valueOf(uploadedCount));
        tvEvaluatedCount.setText(String.valueOf(savedCount + uploadedCount));
    }


    private void showCurrentItemCounts() {
        getEvaluateItemCounts(EVALUATE_LIST_ITEM_SAVED);
        getEvaluateItemCounts(EVALUATE_LIST_ITEM_UPLOADED);
    }


    public void dealWithPushMsg(PushMsgBean msgBean) {

        if (null == pushMsgManager)
            pushMsgManager = PushMsgManager.getInstance(MyApplication.getInstance(), ChannelInfoUtil.getCurrentChannelInfo().getChannel() + UserInfoManager.getInstance(this.getActivity()).getAccount());

        if (msgBean.getNotice_type() == PushMsgManager.MSG_TYPE_QUANMIAN) {

            int msgCount = pushMsgManager.getMsgCount(PushMsgManager.MSG_TYPE_QUANMIAN);
//            if (msgCount == 0) {
//                ivUnevaluateCar.setVisibility(View.GONE);
//            } else {
//                ivUnevaluateCar.setVisibility(View.VISIBLE);
//            }

        } else if (msgBean.getNotice_type() == PushMsgManager.MSG_TYPE_ZHANNEIXIN) {

            int msgCount = pushMsgManager.getMsgCount(PushMsgManager.MSG_TYPE_ZHANNEIXIN);
//            if (msgCount == 0) {
//                ivNotifyUnreadDot.setVisibility(View.GONE);
//            } else {
//                ivNotifyUnreadDot.setVisibility(View.VISIBLE);
//            }

        }

        ((EvaluateHomePageActivity) getActivity()).refreshBottomUnreadMsgCount();

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

}
